﻿//Gets the Window Width and Height
function getWindowWidthHeight()
{
   var result = {};
   result["Width"] = f_clientWidth();
   result["Height"] = f_clientHeight();
   
   return result;
}

//Gets the Window Width
function f_clientWidth() {
	return f_filterResults (
		window.innerWidth ? window.innerWidth : 0,
		document.documentElement ? document.documentElement.clientWidth : 0,
		document.body ? document.body.clientWidth : 0
	);
}

//Gets the Window Height
function f_clientHeight() {
	return f_filterResults (
		window.innerHeight ? window.innerHeight : 0,
		document.documentElement ? document.documentElement.clientHeight : 0,
		document.body ? document.body.clientHeight : 0
	);
}

//Filter function
function f_filterResults(n_win, n_docel, n_body) {
	var n_result = n_win ? n_win : 0;
	if (n_docel && (!n_result || (n_result > n_docel)))
		n_result = n_docel;
	return n_body && (!n_result || (n_result > n_body)) ? n_body : n_result;
}

//Write history
var isDebugMode = false;
function WriteHistory(message)
{
   if (isDebugMode)
   {
	   var historyDiv = document.getElementById('pageHistory');
	   if(historyDiv){
	      while(historyDiv.childNodes.length > 500)
	      {
	         historyDiv.removeChild(historyDiv.lastChild);	      
	      }
		   historyDiv.insertBefore(document.createElement('BR'), historyDiv.firstChild);
		   historyDiv.insertBefore(document.createTextNode(message), historyDiv.firstChild);
	   }
	}
}

function ClearHistory()
{
	var historyDiv = document.getElementById('pageHistory');
	if(historyDiv){
	   historyDiv.innerHTML = "";
	}
}

//set the caret position for a textbox
function setCaretPosition(elemId, caretPos) {
    var elem = document.getElementById(elemId);

    if(elem != null) {
        if(elem.createTextRange) {
            var range = elem.createTextRange();
            range.move('character', caretPos);
            range.select();
        }
        else {
            if(elem.selectionStart) {
                elem.focus();
                elem.setSelectionRange(caretPos, caretPos);
            }
            else
                elem.focus();
        }
    }
}

//hide an element id
function $hide(id)
{
   var element = document.getElementById(id);
   if (element == null)
   {      
      //alert(id + " is invalid");
   }
   else
      element.style.display="none";
}

//show an element id
function $show(id, style, focus)
{
   var element = document.getElementById(id);
   var displayStyle = "block";
   if (style && style != "IGNORE")
   {
      if (style == "NONE")
         displayStyle = "";
      else
         displayStyle =style;
   }
      
   if (element == null)
   {
      //alert(id + " is invalid");
   }
   else
      element.style.display=displayStyle;
      
   if (focus)
   {
      try
      {
         //do a try catch in case element not even visible
         element.focus();
      }
      catch(ex)
      {
      }
   }   
}

//opens new window, takes in url, width, height
function winopen(url, w, h) 
{
  var left = (screen.width) ? (screen.width-w)/2 : 0;
  var top  = (screen.height) ? (screen.height-h)/2 : 0;

  window.open(url, "_blank", "width="+w+",height="+h+",left="+left+",top="+top+",resizable=yes,scrollbars=yes");
  
  return;
}

//opens a generic new window, takes in url
function winopen_withlocationbar(url) 
{
 var w = screen.width / 2;
 var h = screen.height /2;
  var left = (screen.width) ? (screen.width-w)/2 : 0;
  var top  = (screen.height) ? (screen.height-h)/2 : 0;

  window.open(url, "_blank");
  
  return;
}

//opens a new window, takes in url, target window, width, height
function winopen2(url,target, w, h) 
{
  var left = (screen.width) ? (screen.width-w)/2 : 0;
  var top  = (screen.height) ? (screen.height-h)/2 : 0;

 if(popupWin_2[target] != null)
	if(!popupWin_2[target].closed)
		popupWin_2[target].focus();
	else
		popupWin_2[target] = window.open(url, target, "width="+w+",height="+h+",left="+left+",top="+top+",resizable=yes,scrollbars=yes");
  else
	popupWin_2[target] = window.open(url, target, "width="+w+",height="+h+",left="+left+",top="+top+",resizable=yes,scrollbars=yes");
  
  return;
}

function removeChildNodes(element)
{
   while(element.firstChild)
      element.removeChild(element.firstChild);
}

function installScript( script )
{
    if (!script)
        return;

     WriteHistory("installScript: " + script);
     //  Internet Explorer has a funky execScript method that makes this easy
     if (window.execScript)
         window.execScript( script);
     else
         window.setTimeout( script, 0 );
}

var installScriptSrc_Dict = new Object();
function installScriptSrc_CheckLoaded(src)
{
   src = makeAbsoluteKey(src);
   WriteHistory("installScriptSrc_CheckLoaded: " + src);
   
   var result = installScriptSrc_Dict[src];
   WriteHistory(src + " : " + result);
   if (result)
      return result;
   else
      return false;
}

function installScriptSrc_UpdateDict(obj)
{
   var src = makeAbsoluteKey(obj.src)
   WriteHistory("installScriptSrc_UpdateDict: " + src);
   if (is_ie)
   {
      //Wierd IE bug, does not seem to load immediately, so have to queue this thing..
      WriteHistory("installScriptSrc_Dict['" + src + "'] = true;");
      setTimeout("installScriptSrc_Dict['" + src + "'] = true;", 1000);
   }
   else
   {
      installScriptSrc_Dict[src] = true;
   }
   //installScriptSrc_ToString();
}

function installScriptSrc_ToString()
{
   var obj = installScriptSrc_Dict;
   for(var key in obj)
   {
      WriteHistory(key + " : " + obj[key]);
   }
}
function makeAbsolute(src)
{
   if (src)
   {
      WriteHistory("makeAbsolute-b4: " + src);
      src = src.toLowerCase();
      if (src.indexOf("http") == 0)
      {
         //starts with http, ignore
      }
      else if (src[0] == "/")
      {
         //starts with absolute path, add http://...
         var x = "";
         
         var path = location.href.toLowerCase().replace(location.pathname.toLowerCase() + location.search.toLowerCase(), "");
         
         src = path + src;
      }
      else
      {
         //is relative path, get from last /
         src = location.href.substring(0, location.href.lastIndexOf("/")) + src;
      }
      
      WriteHistory("makeAbsolute-after: " + src);
      return src.toLowerCase();
   }
   else
      return "";
}
function makeAbsoluteKey(src)
{
   return makeAbsolute(src).replace(/\//g, "_").replace(/\?/g, "_").replace(/\&/g, "_").replace(/\%/g, "_");
}

function installScriptSrc(src)
{
   WriteHistory("installScriptSrc:" + src);
   var src2 = makeAbsolute(src);
   WriteHistory("installScriptSrc #2: " + src2);
   
   var Scripts = document.getElementsByTagName("script");
   for(var i=0;i<Scripts.length;i++)
   {
      if (Scripts[i].src)
      {
         if (makeAbsolute(Scripts[i].src) == src2)
         {
            //only add scripts that are new
            WriteHistory("installScriptSrc:" + src + " already exists");
            return;
         }
      }
   }
   var head = document.getElementsByTagName("head")[0];
   var scriptObj = document.createElement("script");
   scriptObj.setAttribute("type", "text/javascript");
   scriptObj.setAttribute("src", src);
   //scriptObj.defer = true;  
   head.appendChild(scriptObj);
   if (is_ie)
   {
      scriptObj.onreadystatechange=function() {
         //alert(this.readyState);
         if (this.readyState == 'loaded' || this.readyState == 'complete')
         {
            installScriptSrc_UpdateDict(this)
         }
      }
   }
   else
   {
      scriptObj.onload=function () {installScriptSrc_UpdateDict(this)}
   }
   WriteHistory("Added" + src2);
}


function grabContent(theURL, FunctionToCall)
{
       var request = new Sys.Net.WebRequest();
       request.set_httpVerb("GET");
      request.set_url(theURL);
       request.add_completed( function( executor )
       {
           if (executor.get_responseAvailable()) 
           {
               var content = executor.get_responseData();
               FunctionToCall(content);
           }
       });
       
       var executor = new Sys.Net.XMLHttpExecutor();
       request.set_executor(executor); 
       executor.executeRequest();
}

function removeAllAttributesFromChild(Element, attribute)
{
   if (Element.childNodes)
   {
      var ttl = Element.childNodes.length;
      for(var i=0;i<ttl;i++)
      {
         var e = Element.childNodes[i];
         try
         {
         e.removeAttribute(attribute);
         }
         catch(ex)
         {
         }
      }
   }
}

function setAllAttributesForChild(Element, attribute, value)
{
   if (Element.childNodes)
   {
      var ttl = Element.childNodes.length;
      for(var i=0;i<ttl;i++)
      {
         var e = Element.childNodes[i];
         e.setAttribute(attribute, value);
      }
   }
}

function MenuItem_Click(Element, AttributeToSetValue)
{
   var ElementToIgnore = Element;
   Element = Element.parentNode;
   var ttl = Element.childNodes.length;
   var AttributeToRemove = "classx"
   for(var i=0;i<ttl;i++)
   {
      var e = Element.childNodes[i];
      if (e != ElementToIgnore)
      {
         if (e.removeAttribute)
         {
            e.removeAttribute(AttributeToRemove);
         }

         e.className = AttributeToSetValue;
      }
   }
   ElementToIgnore.setAttribute("classx", ElementToIgnore.className);
}

function MenuItem_OnMouseOut(Element, className)
{
   var cls = Element.getAttribute('classx');
   if(cls==null)
      cls='';
   Element.className=(cls.length > 0 ? cls : className);
}

function setElementToAjaxLoading(Element)
{
   removeChildNodes(Element);
   var x = "<img src='/images/ajax_bar.gif' border='0' />";
   if (arguments.length > 1)
   {
      x = arguments[1] + x + arguments[2];
   }
   Element.innerHTML = x;
}

function getElementHeight(Element) {
if(Element.clientHeight) {return Element.clientHeight;}
else if(Element.offsetHeight) {return Element.offsetHeight;}
return -1;
}

function getElementWidth(Element) {
if(Element.clientWidth && parseInt(Element.clientWidth)>0) {return parseInt(Element.clientWidth);}
else {if(Element.offsetWidth) {return parseInt(Element.offsetWidth);}}
return 0;
}

function getClickEventProperties(e)
{
	var posx = 0;
	var posy = 0;
	if (!e) var e = window.event;
	if (e.pageX || e.pageY) 	{
		posx = e.pageX;
		posy = e.pageY;
	}
	else if (e.clientX || e.clientY) 	{
		posx = e.clientX + document.body.scrollLeft
			+ document.documentElement.scrollLeft;
		posy = e.clientY + document.body.scrollTop
			+ document.documentElement.scrollTop;
	}

   var targ = null;	
	if (e.target) targ = e.target;
	else if (e.srcElement) targ = e.srcElement;
	if (targ.nodeType == 3) // defeat Safari bug
		targ = targ.parentNode;	
		
	var result = {};
	result.x = posx;
	result.y = posy;
	result.target = targ;
	
	return result;
}

//Drop down menu code
var mTimeOut = 0;
var mCurrentItem = null;
var mTargets = new Array();

function Menu_AddTarget(src, target)
{
   WriteHistory("Menu_AddTarget: " + src + " : " + target);
   src = src.toLowerCase();
   target = target.toLowerCase();
   for(var i=0;i<mTargets.length;i++)
   {
      if (src == mTargets[i].src)
      {
         mTargets[i].target.onmouseout = null;
         
         mTargets[i].target = target;
         Menu_Setup(mTargets[i]);
         return;
      }
   }
   
   var obj = {};
   obj.src = src;
   obj.target = target;
   obj.Active = false;
   mTargets.push(obj);
   Menu_Setup(obj);
}

function Menu_FindItem(src)
{
   if (src != null)
   {
      for(var i=0;i<mTargets.length;i++)
      {
         //WriteHistory("FindTarget: " + i + ":" + src + ":" + mTargets[i].src + ":" + mTargets[i].target);
         if (src.toLowerCase() == mTargets[i].src)
         {
            return mTargets[i];
         }
      }
   }
   return null;
}

function Menu_FindTarget(src)
{
   var item = Menu_FindItem(src);
   if (item)
      return item.target;
   else
      return null;
}

function Menu_Setup(obj)
{
   var js = "$('" + obj.src + "').onmouseout=function() {collapse('" + obj.src + "')};";
   js += "$('" + obj.target + "').onmouseout=function() {collapse('" + obj.src + "')};";
   $(obj.target).onmouseover=cancelcollapse;
   $(obj.src).onclick=expand;
   installScript(js);
}

function expand(e)
{
   var x1 = getClickEventProperties(e);
   
   if (mCurrentItem != null)
   {
      //collapse previous menu
      collapseMenu(mCurrentItem);
   }
   //set current menu to current item
   mCurrentItem = x1.target.id;
   
   var Bounds = Sys.UI.DomElement.getBounds(x1.target);
   
   var browser = window.navigator.appName;
   var dif = 0;
   if (browser != "Microsoft Internet Explorer") { dif = 4; }

   var ClickElement = x1.target;
   var TargetItem = Menu_FindItem(x1.target.id);
   WriteHistory("expand: " + TargetItem.src + ":" + TargetItem.target + ":" + TargetItem.Active);
   var TargetID = TargetItem.target;
   if (TargetID == null)
   {
      WriteHistory("Error:" + x1.x + ":" + x1.y + ":" + x1.target + ":" + x1.target.id + ":" + ClickElement.id + ":");
      return;
   }
   
   TargetItem.Active = true;
   var MenuDiv = document.getElementById(Menu_FindTarget(x1.target.id));

   MenuDiv.style.position = "absolute";
   MenuDiv.style.visibility = "visible";
   MenuDiv.style.display = "block";
   
   var WindowWH = getWindowWidthHeight();
   if (WindowWH.Width > Bounds.x + 100)
   {
      MenuDiv.style.left = Bounds.x + "px";
      MenuDiv.style.right = "";
      MenuDiv.style.top = (Bounds.y + Bounds.height + dif) + "px"; 
   }
   else
   {
      MenuDiv.style.left = "";
      MenuDiv.style.right = (WindowWH.Width - Bounds.x - Bounds.width) + "px";
      MenuDiv.style.top = (Bounds.y + Bounds.height + dif) + "px"; 
   }
   
   //WriteHistory(MenuDiv.style.left + ":" + MenuDiv.style.top);
   //MenuDiv.style.width = "auto";
}

function collapseMenu(s)
{
   var TargetItem = Menu_FindItem(s);
   if (TargetItem.Active)
   {
      TargetItem.Active = false;
      var d = document.getElementById(TargetItem.target);
      if (d != null)
      {
         mCurrentItem =  null;
         //d.style.position = "static";
         d.style.visibility = "hidden";
         d.style.display = "none";
      }
   }
}

function collapse(s)
{
   var TargetItem = Menu_FindItem(s);
   if (TargetItem && TargetItem.Active)
   {      
      var d = document.getElementById(TargetItem.target);
      if (d != null)
      {
         mTimeOut = window.setTimeout("collapseMenu('" + s + "')", 1000);
         //WriteHistory("collapse: " + s + ":" + mTimeOut);
      }
   }
}

function cancelcollapse()
{
   //WriteHistory("cancelcollapse: " + mTimeOut);
   if (mTimeOut > 0)
   {
      window.clearInterval(mTimeOut);
      //WriteHistory("cancelcollapse-clear: " + mTimeOut);
      mTimeOut = 0;
   }
}


function XmlToObject(content)
{
      var xmlDoc = null;
      try //Internet Explorer
      {
         xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
         xmlDoc.async = false;
         xmlDoc.loadXML(content);
      }
      catch(e)
      {
         try //Firefox, Mozilla, Opera, etc.
         {
            parser=new DOMParser();
            xmlDoc=parser.parseFromString(content,"text/xml");
         }
         catch(e) {alert(e.message)}
      }
      
      if (xmlDoc.childNodes.length > 0)
      {
         var xStatus = xmlDoc.getElementsByTagName("status")[0];
         var status = (xStatus.length > 0 ? xStatus.firstChild.nodeValue : "");
         
         var Communities = xmlDoc.getElementsByTagName("row");
         var strCommunities = "<ul>";
         for(var i=0;i<Communities.length;i++)
         {
            strCommunities += "<li><a target='_blank' href='https://u.nus.edu.sg" + Communities[i].childNodes[0].childNodes[0].nodeValue + "'>" +
                           Communities[i].childNodes[1].childNodes[0].nodeValue + 
                           "</li>";
            
         }
         strCommunities += "</ul>";
      }
      
      xmlDoc = null;
}


function XMLObjTree_ItemArray(Node)
{
   if (Node)
   {
      if (Node.length)
      {
         return Node;
      }
      else
      {
         var result = new Array();
         result.push(Node);      
         return result;
      }
   }
   else
      return null;
}


function URLEncode(URL)
{
	// The Javascript escape and unescape functions do not correspond
	// with what browsers actually do...
	var SAFECHARS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_.!~*'()";
	var HEX = "0123456789ABCDEF";

	var plaintext = URL;
	var encoded = "";
	for (var i = 0; i < plaintext.length; i++ ) {
		var ch = plaintext.charAt(i);
	    if (ch == " ") {
		    encoded += "+";				// x-www-urlencoded, rather than %20
		} else if (SAFECHARS.indexOf(ch) != -1) {
		    encoded += ch;
		} else {
		    var charCode = ch.charCodeAt(0);
			if (charCode > 255) {
			    alert( "Unicode Character '" 
                        + ch 
                        + "' cannot be encoded using standard URL encoding.\n" +
				          "(URL encoding only supports 8-bit characters.)\n" +
						  "A space (+) will be substituted." );
				encoded += "+";
			} else {
				encoded += "%";
				encoded += HEX.charAt((charCode >> 4) & 0xF);
				encoded += HEX.charAt(charCode & 0xF);
			}
		}
	} // for

	return encoded;
};

var dDefaultBtn = new Object();

function setDefaultButton(Input, Button)
{
   var isNew = true;
   for(var key in dDefaultBtn)
   {
      if (key == Input.toLowerCase())
      {
         isNew = false;
      }
   }
   
   if(isNew)
   {
      $(Input).onkeydown = fnTrap;
      dDefaultBtn[Input.toLowerCase()] = $(Button);
   }
}

function fnTrap(e)
{
	if (!e) var e = window.event;
   var keyCode = e.keyCode;   
   var target = e.target;
   if(target && target.id)
   {
      for(var key in dDefaultBtn)
      {
         if (key == target.id.toLowerCase())
         {
            fnTrapKD(dDefaultBtn[key], e);         
         }
      }
   }
}

function fnTrapKD(btn, event){
 if (document.all){
  if (event.keyCode == 13){
   event.returnValue=false;
   event.cancel = true;
   btn.click();
  }
 }
 else if (document.getElementById){
  if (event.which == 13){
   event.returnValue=false;
   event.cancel = true;
   btn.click();
  }
 }
 else if(document.layers){
  if(event.which == 13){
   event.returnValue=false;
   event.cancel = true;
   btn.click();
  }
 }
}

function AddRSS()
{
   var e = $('RSS_XmlFile');
   var b = $('btn_RSS');
   if (e.value.length > 0)
   {
      myWidgets.AddRSS(e.value);
      //Menu.Hide();
      b.disabled = true;
      b.value = "Please wait while we add this rss to your tab...";
      
      setTimeout("var e = $('RSS_XmlFile');var b = $('btn_RSS');b.disabled=false;b.value='Add RSS to this Tab';e.value = '';", 1500);
   }
   else
   {
      alert("Please enter a RSS URL");
   }
}

//Generic function to enable tooltip for any element
function DoTip(Element, theTip)
{
   Element.onmouseover = function() {Tip(theTip, BALLOON, true);}
   Element.onmouseout = function() {UnTip();}
}

function execJS(node)
{
  var bSaf = is_safari;
  var bOpera = is_opera;
  var bMoz = is_moz;

  if (!node) return;

  /* IE wants it uppercase */
  var st = node.getElementsByTagName('SCRIPT');
  var strExec;
   var ItemsToRemove = new Array();
  for(var i=0;i<st.length; i++)
  {
   WriteHistory("Found: " + st[i]);
   if (st[i].src)
   {
      //special case.. need to remove and add back the child???
      WriteHistory("SRC: " + st[i].src);
      
      //cannot use install script src because it loads at the top, which may not be the intention
      //installScriptSrc(theSRC);

      //clone a new node
      var theSRC = st[i].src;
      st[i].src = "";
      
      var e = document.createElement('script');
      e.type = 'text/javascript';
      e.src = theSRC;
      
      //insert this new node right after the original node
      var theParent = st[i].parentNode;
      
      if (theParent)
      {
         theParent.insertBefore(e, st[i]);
         WriteHistory("insert");      
         
         //remove the original node
         theParent.removeChild(st[i]);
         WriteHistory("remove");
      }
      
   }
   else
   {
     //WriteHistory("Script: " + st[i]);

       if (bSaf) {
         strExec = st[i].innerHTML;
         st[i].innerHTML = "";
       } else if (bOpera) {
         strExec = st[i].text;
         st[i].text = "";
       } else if (bMoz) {
         strExec = st[i].textContent;
         st[i].textContent = "";
       } else {
         strExec = st[i].text;
         st[i].text = "";
       }

       try {
         installScript(strExec);
         /*
         var x = document.createElement("script");
         x.type = "text/javascript";

         /* In IE we must use .text! */
         /*
         if ((bSaf) || (bOpera) || (bMoz))
           x.innerHTML = strExec;
         else x.text = strExec;

         //document.getElementsByTagName("head")[0].appendChild(x);
         installScript(strExec);
         */
       } catch(e) {
         alert(e);
       }
   }
  }
};